#!/usr/bin/env python
import atlasgen as atl
import cPickle
import string
import sys
from optparse import OptionParser
def getParser():
    parser = OptionParser()
    parser.add_option("-a","--atlas_list",dest='atlas',
                      help='file containing...',
                      default='atlas_list')
    parser.add_option('-i','--img_list',dest='images',default='img_list',
                      help='file containing list of images to ...')

    return parser
def main():
    parser = getParser()
    (options, args) = parser.parse_args()	
    fo = file(options.atlas,'r')
    atlaslist = fo.readlines()		#atlaslist= [line1\n, line2\n, line3\n...]
    fo.close()
    ifo = file(options.images,'r')
    imglist = ifo.readlines()
    ifo.close()
    
    #clean lists of '\n'
    for line in range(len(atlaslist)):
        atlaslist[line] = string.split(atlaslist[line],'\n')[0]
        print "{0}".format(atlaslist[line])
        imglist[line] = string.split(imglist[line],'\n')[0]
        print imglist[line]
    
    print atlaslist
    for line in range(len(atlaslist)):
    
        #load
        gfo = file(atlaslist[line],'rb')
        graph = cPickle.load(gfo)
    
        #rename
        name = string.split(atlaslist[line],'.pckle')[0]
        print name
        name = '{0}_tr.pckle'.format(name)
        print name
    
        #recenter
        graph = atl.center_graph(graph,imglist[line])
        og = graph['orderedGraphs'][(1,'mp_graphs')]
        print og.nodes(True)
    
        #centered check
        nodes = og.nodes(data=True)
        for n in nodes:
            if n[1]['rank'] == 0:
                if n[1]['trwcrd'].all():			#if not np.array([0,0,0])
                    print 'precheck failed for:',atlaslist[line]
                    print n[1]['trwcrd']
                    return 1
                else:
                    print 'precheck cleared for:',atlaslist[line]
                    break	
    
        #save under new name
        nfo = file(name,'wb')
        cPickle.dump(graph,nfo)
        nfo.close()
    
    return 0

if __name__== "__main__":
	main()
#-----------------------END OF PROGRAM------------------------
